﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.AddIn.Hosting;
using Toolbox.Plugin;
using Toolbox.Plugin.Interfaces;
using System.IO;
using System.ComponentModel.Composition;
using System.ComponentModel;
using System.Diagnostics;

namespace Toolbox.Plugin.Thread
{
    [PluginDescription("File handling thread"), PluginThread(10)]
    public class FileHandlerThread : PluginThread, IPluginThread
    {
        [ImportMany]
        public PluginInstances<IPluginFileHandler> Source { get; set; }

        [ImportMany]
        public PluginInstances<IPluginFileHandler> Target { get; set; }

        public DateTime StartDate { get; set; }
        public int BatchSize { get; set; }

        #region ISupportInitialize Members

        public override void BeginInit()
        {
            base.BeginInit();
        }

        public override void EndInit()
        {
            base.EndInit();

            if (!this.DesignMode)
            {
                if (this.Source is PluginInstances<IPluginFileHandler> && this.Source.Values.Length > 0)
                {
                    foreach (IPluginFileHandler f in this.Source.Values)
                    {
                        f.SetProperty("BatchSize", this.BatchSize);
                        f.SetProperty("CurrentDate", this.StartDate);
                    }
                }
                else
                {
                    throw new InvalidDataException("Source not specified for '" + this.GetType().FullName + "'");
                }

                if (this.Target is PluginInstances<IPluginFileHandler> && this.Target.Values.Length > 0)
                {
                    foreach (IPluginFileHandler f in this.Target.Values)
                    {
                        f.SetProperty("BatchSize", this.BatchSize);
                        f.SetProperty("CurrentDate", this.StartDate);
                    }
                }
                else
                {
                    throw new InvalidDataException("Target not specified for '" + this.GetType().FullName + "'");
                }
            }
        }

        #endregion

        public override void OnRunLoop()
        {
            string[] l = this.Source.Values[0].List();

            Trace.TraceInformation("Transfering " + l.Length.ToString() + " files...");

            if (l.Length > 0)
            {
                this.Source.Values[0].Get(ref l);
                this.Target.Values[0].Put(l);
            }

            Trace.TraceInformation("Transfer done!");
        }
    }

}
